package com.kelvin.oocl.filemanager.client;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;

import com.kelvin.oocl.filemanager.constant.Constant;

public class FileClient {
	
	public void startUp(){
		Scanner scanner = new Scanner(System.in);
		try {
			while(true){
				System.out.println("Pls input scp command->");
				String line = scanner.nextLine().trim();
				if(line.startsWith("scp")){
					uploadFile(line);
				}else {
					System.out.println("command wrong!");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IndexOutOfBoundsException e) {
			e.printStackTrace();
		}
	}

	private void uploadFile(String line) throws IOException,IndexOutOfBoundsException{
		String[] strs = line.split("\\s+");
		String ip = strs[2];
		Socket socket = new Socket(ip,8888);
		BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
		BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
		out.write((Constant.SCP+Constant.ENTER).getBytes());
		out.flush();
		reader.readLine();
		out.write((strs[3]+"\r\n").getBytes());
		out.flush();
		reader.readLine();
		
		BufferedInputStream in1 = new BufferedInputStream(new FileInputStream(strs[1]));
		byte[] buf = new byte[64];
		int n=-1;
		int len = 0;
		while((n = in1.read(buf))!=-1){
			len = n;
			out.write(buf,0,n);
		}
		if(len<64){
			byte[] buf1 = new byte[64-len];
			for(int i=0;i<64-len;i++){
				buf[i]=-1;
			}
			out.write(buf1);
		}
		byte[] buf2 = new byte[64];
		buf2[0]=Byte.MIN_VALUE;
		for(int i=1;i<64;i++){
			buf[i]=-1;
		}
		out.write(buf2);
		out.flush();
		
		String str2 = reader.readLine();
		System.out.println(str2);
	}
}

